import { create } from 'zustand';
import { devtools } from 'zustand/middleware';
import { PromptTemplate, PromptVersion, PromptVariable } from '@/types/prompt';
import { promptService } from '@/services/prompt.service';
import { message } from 'antd';

interface PromptState {
  // 状态
  prompts: PromptTemplate[];
  currentPrompt: PromptTemplate | null;
  versions: PromptVersion[];
  isEditing: boolean;
  isLoading: boolean;
  draftContent: string;
  draftVariables: PromptVariable[];
  recentPrompts: string[];  // IDs of recently used prompts
  favoritePrompts: string[];  // IDs of favorite prompts
  
  // Actions
  loadPrompts: () => Promise<void>;
  selectPrompt: (id: string) => void;
  createPrompt: (prompt: Partial<PromptTemplate>) => Promise<void>;
  updatePrompt: (id: string, updates: Partial<PromptTemplate>) => Promise<void>;
  deletePrompt: (id: string) => Promise<void>;
  toggleFavorite: (id: string) => void;
  addToRecent: (id: string) => void;
  saveVersion: (changelog?: string, tag?: string) => Promise<void>;
  loadVersionHistory: (promptId: string) => Promise<void>;
  applyVersion: (versionId: string) => void;
  deleteVersion: (versionId: string) => Promise<void>;
  setDraftContent: (content: string) => void;
  setDraftVariables: (variables: PromptVariable[]) => void;
  setEditing: (isEditing: boolean) => void;
  clearDraft: () => void;
  
  // Version management
  compareVersions: (v1Id: string, v2Id: string) => { v1: PromptVersion; v2: PromptVersion } | null;
  rollbackToVersion: (versionId: string) => Promise<void>;
  exportPrompt: (promptId: string) => Promise<string>;
  importPrompt: (data: string) => Promise<void>;
  
  // Statistics
  incrementUsageCount: (promptId: string) => void;
  trackSuccess: (promptId: string, success: boolean) => void;
  getStatistics: (promptId: string) => Promise<any>;
}

export const usePromptStore = create<PromptState>()(
  devtools(
    (set, get) => ({
      // Initial state
      prompts: [],
      currentPrompt: null,
      versions: [],
      isEditing: false,
      isLoading: false,
      draftContent: '',
      draftVariables: [],
      recentPrompts: JSON.parse(localStorage.getItem('recentPrompts') || '[]'),
      favoritePrompts: JSON.parse(localStorage.getItem('favoritePrompts') || '[]'),

      // Load all prompts
      loadPrompts: async () => {
        set({ isLoading: true });
        try {
          const response = await promptService.getPrompts();
          set({ prompts: response.data, isLoading: false });
        } catch (error) {
          message.error('加载提示词失败');
          set({ isLoading: false });
        }
      },

      // Select a prompt
      selectPrompt: (id: string) => {
        const prompt = get().prompts.find(p => p.id === id);
        if (prompt) {
          set({ 
            currentPrompt: prompt,
            draftContent: prompt.systemPrompt,
            draftVariables: prompt.variables
          });
        }
      },

      // Create new prompt
      createPrompt: async (prompt: Partial<PromptTemplate>) => {
        try {
          const newPrompt = await promptService.createPrompt(prompt);
          set(state => ({
            prompts: [...state.prompts, newPrompt],
            currentPrompt: newPrompt
          }));
          message.success('提示词已创建');
        } catch (error) {
          message.error('创建提示词失败');
        }
      },

      // Update prompt
      updatePrompt: async (id: string, updates: Partial<PromptTemplate>) => {
        try {
          const updatedPrompt = await promptService.updatePrompt(id, updates);
          set(state => ({
            prompts: state.prompts.map(p => p.id === id ? updatedPrompt : p),
            currentPrompt: state.currentPrompt?.id === id ? updatedPrompt : state.currentPrompt
          }));
          message.success('提示词已更新');
        } catch (error) {
          message.error('更新提示词失败');
        }
      },

      // Delete prompt
      deletePrompt: async (id: string) => {
        try {
          await promptService.deletePrompt(id);
          set(state => ({
            prompts: state.prompts.filter(p => p.id !== id),
            currentPrompt: state.currentPrompt?.id === id ? null : state.currentPrompt
          }));
          message.success('提示词已删除');
        } catch (error) {
          message.error('删除提示词失败');
        }
      },

      // Save version
      saveVersion: async (changelog?: string, tag?: string) => {
        const { currentPrompt, draftContent, draftVariables } = get();
        if (!currentPrompt) {
          message.error('请先选择一个提示词');
          return;
        }

        try {
          const version = await promptService.saveVersion(currentPrompt.id, {
            content: draftContent,
            variables: draftVariables,
            changelog,
            tag
          });
          
          set(state => ({
            versions: [...state.versions, version],
            currentPrompt: {
              ...state.currentPrompt!,
              version: version.version,
              systemPrompt: draftContent,
              variables: draftVariables
            }
          }));
          
          message.success('版本已保存');
        } catch (error) {
          message.error('保存版本失败');
        }
      },

      // Load version history
      loadVersionHistory: async (promptId: string) => {
        set({ isLoading: true });
        try {
          const versions = await promptService.getVersionHistory(promptId);
          set({ versions, isLoading: false });
        } catch (error) {
          message.error('加载版本历史失败');
          set({ isLoading: false });
        }
      },

      // Apply version
      applyVersion: (versionId: string) => {
        const version = get().versions.find(v => v.id === versionId);
        if (version) {
          set(state => ({
            draftContent: version.content,
            draftVariables: version.variables,
            currentPrompt: state.currentPrompt ? {
              ...state.currentPrompt,
              systemPrompt: version.content,
              variables: version.variables,
              version: version.version
            } : null
          }));
          message.success(`已切换到版本 v${version.version}`);
        }
      },

      // Delete version
      deleteVersion: async (versionId: string) => {
        try {
          await promptService.deleteVersion(versionId);
          set(state => ({
            versions: state.versions.filter(v => v.id !== versionId)
          }));
          message.success('版本已删除');
        } catch (error) {
          message.error('删除版本失败');
        }
      },

      // Set draft content
      setDraftContent: (content: string) => {
        set({ draftContent: content });
      },

      // Set draft variables
      setDraftVariables: (variables: PromptVariable[]) => {
        set({ draftVariables: variables });
      },

      // Set editing state
      setEditing: (isEditing: boolean) => {
        set({ isEditing });
      },

      // Clear draft
      clearDraft: () => {
        set({ draftContent: '', draftVariables: [], isEditing: false });
      },

      // Compare versions
      compareVersions: (v1Id: string, v2Id: string) => {
        const { versions } = get();
        const v1 = versions.find(v => v.id === v1Id);
        const v2 = versions.find(v => v.id === v2Id);
        
        if (v1 && v2) {
          return { v1, v2 };
        }
        return null;
      },

      // Rollback to version
      rollbackToVersion: async (versionId: string) => {
        const version = get().versions.find(v => v.id === versionId);
        if (!version || !get().currentPrompt) {
          message.error('版本或提示词不存在');
          return;
        }

        try {
          await promptService.rollbackToVersion(get().currentPrompt!.id, versionId);
          get().applyVersion(versionId);
          message.success('已回滚到指定版本');
        } catch (error) {
          message.error('回滚失败');
        }
      },

      // Export prompt
      exportPrompt: async (promptId: string) => {
        try {
          const data = await promptService.exportPrompt(promptId);
          return JSON.stringify(data, null, 2);
        } catch (error) {
          message.error('导出失败');
          throw error;
        }
      },

      // Import prompt
      importPrompt: async (data: string) => {
        try {
          const promptData = JSON.parse(data);
          const imported = await promptService.importPrompt(promptData);
          set(state => ({
            prompts: [...state.prompts, imported]
          }));
          message.success('导入成功');
        } catch (error) {
          message.error('导入失败');
        }
      },

      // Increment usage count
      incrementUsageCount: (promptId: string) => {
        set(state => ({
          prompts: state.prompts.map(p => 
            p.id === promptId 
              ? { ...p, usageCount: (p.usageCount || 0) + 1 }
              : p
          )
        }));
      },

      // Track success
      trackSuccess: async (promptId: string, success: boolean) => {
        try {
          await promptService.trackSuccess(promptId, success);
        } catch (error) {
          console.error('Failed to track success:', error);
        }
      },

      // Get statistics
      getStatistics: async (promptId: string) => {
        try {
          return await promptService.getStatistics(promptId);
        } catch (error) {
          message.error('获取统计数据失败');
          return null;
        }
      },

      // Toggle favorite
      toggleFavorite: (id: string) => {
        set(state => {
          const favorites = [...state.favoritePrompts];
          const index = favorites.indexOf(id);
          if (index > -1) {
            favorites.splice(index, 1);
          } else {
            favorites.push(id);
          }
          localStorage.setItem('favoritePrompts', JSON.stringify(favorites));
          return { favoritePrompts: favorites };
        });
      },

      // Add to recent
      addToRecent: (id: string) => {
        set(state => {
          const recent = [...state.recentPrompts];
          const index = recent.indexOf(id);
          if (index > -1) {
            recent.splice(index, 1);
          }
          recent.unshift(id);
          // Keep only last 10 recent prompts
          const limitedRecent = recent.slice(0, 10);
          localStorage.setItem('recentPrompts', JSON.stringify(limitedRecent));
          return { recentPrompts: limitedRecent };
        });
      }
    }),
    {
      name: 'prompt-store'
    }
  )
);